'use client';
import './index.css';
import Image from 'next/image';
import { LoginForm, ProForm, ProFormText } from '@ant-design/pro-form';
import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import Link from 'next/link';
import { message } from 'antd';
import { useRouter } from 'next/navigation';
import { registerUsingPost } from '@/api/UserApi';

const UserRegisterPage: React.FC = () => {
  const router = useRouter();
  const [form] = ProForm.useForm();
  const handleRegister = async (regForm: API.RegisterDto) => {
    if (regForm.password !== regForm.checkPassword) {
      message.warning('两次输入的密码不一致');
      return;
    }
    try {
      const res = await registerUsingPost(regForm);
      if (res) {
        message.success('注册成功');
        router.replace('/user/login');
        form.resetFields();
      }
    } catch (e) {
      message.error('注册失败。' + e.message);
    }
  };
  return (
    <div id="login-page">
      <LoginForm
        form={form}
        logo={<Image src="/assets/logo.png" alt="" height={44} width={44} />}
        title="NextJS - 用户注册"
        subTitle="程序员面试刷题网站"
        onFinish={handleRegister}
        submitter={{
          searchConfig: {
            submitText: '注册',
          },
        }}
      >
        <ProFormText
          name="username"
          fieldProps={{
            size: 'large',
            prefix: <UserOutlined />,
          }}
          placeholder={'请输入用户名'}
          rules={[
            {
              required: true,
              message: '请输入用户名!',
            },
          ]}
        />
        <ProFormText.Password
          name="password"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入密码'}
          rules={[
            {
              required: true,
              message: '请输入密码！',
            },
          ]}
        />
        <ProFormText.Password
          name="checkPassword"
          fieldProps={{
            size: 'large',
            prefix: <LockOutlined />,
          }}
          placeholder={'请输入确认密码'}
          rules={[
            {
              required: true,
              message: '请输入确认密码！',
            },
          ]}
        />
        <div
          style={{
            marginBlockEnd: 24,
            textAlign: 'end',
          }}
        >
          已有账号?
          <Link href={'/user/login'}>去登录</Link>
        </div>
      </LoginForm>
    </div>
  );
};

export default UserRegisterPage;
